﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Tools
{
    public class ZCoolWebUtils
    {
        // 用于存储图片的ImageList
        public ImageList ImageList { get; private set; }

        // 存储图片的URL列表
        public List<string> ImageUrls { get; private set; }

        public ZCoolWebUtils()
        {
            ImageList = new ImageList();
            // 设置ImageList的图片大小
            ImageList.ImageSize = new Size(100, 100);
            ImageUrls = new List<string>();
        }

        /// <summary>
        /// 从网页URL提取所有WebP图片链接
        /// </summary>
        public List<string> ExtractWebpUrlsFromWebPage(HtmlAgilityPack.HtmlDocument _source)
        {
            try
            {
               

                var _images = _source.DocumentNode.SelectNodes(".//div[contains(@class,'jivDXX')]//img[contains(@class,'photoImage')]");

                foreach (var img in _images)
                {
                    var abc = img;

                    this.ImageUrls.Add(img.Attributes["data-src"].Value);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"提取图片URL时出错: {ex.Message}");
            }

            return ImageUrls;
        }

        /// <summary>
        /// 下载WebP图片并添加到ImageList
        /// </summary>
        public void DownloadAndAddWebpImages()
        {
            ImageList.Images.Clear();

            using (WebClient client = new WebClient())
            {
                foreach (string url in ImageUrls)
                {
                    try
                    {
                        // 下载图片数据
                        byte[] imageData = client.DownloadData(url);

                        // 将字节数组转换为Image
                        using (MemoryStream ms = new MemoryStream(imageData))
                        {
                            // 使用Image.FromStream加载WebP
                            // 注意：.NET Framework可能需要额外组件支持WebP
                            Image image = Image.FromStream(ms);

                            // 添加到ImageList
                            ImageList.Images.Add(image);
                            Console.WriteLine($"成功加载图片: {url}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"加载图片 {url} 时出错: {ex.Message}");
                    }
                }
            }
        }

        /// <summary>
        /// 直接添加指定的WebP图片URL到ImageList
        /// </summary>
        public void AddWebpImagesFromUrls(List<string> urls)
        {
            ImageUrls.AddRange(urls);
            DownloadAndAddWebpImages();
        }
    }
}
